<template>
	<view class="shelf-box">
		<view class="status-bar" :style="{ height: iStatusBarHeight + 'px'}"></view>
		<view class="load" v-if="loading">
			<u-loading mode="circle" size="50" color="rgb(146, 200, 255)" style="position: relative;bottom:100rpx;"></u-loading>
		</view>
		<u-navbar :is-back="false" title="" v-show="!editFlag">
			<view class="read-time">
				<text @click="handleToReadTime">您已阅读{{readTime}}分钟</text>
			</view>
			<view class="slot-wrap">
				<u-icon name="search" size="40" style="margin-right: 20rpx;" @click="handleToSearch"></u-icon>
				<u-icon name="clock" size="40" style="margin-right: 20rpx;" @click="handleToHistory"></u-icon>
				<u-icon name="edit-pen" color="#061B41" size="40" @click="handleToEdit"></u-icon>
				<!-- <u-icon name="plus" size="40" @click="handleToOpen"></u-icon> -->
			</view>
		</u-navbar>
		<u-navbar :back-text="checkAllFlag?'全选':'取消全选'" back-icon-name="" v-show="editFlag" :custom-back="handleToCheckedAll">
			<view class="edit-wrap">
				<text style="font-size: 30rpx;font-weight: bold;" @click="handleToSave">完成</text>
			</view>
		</u-navbar>
		<view class="bookshelf-content">
			<u-row justify="start" align="top" v-if="bookshelfList.length > 0">
				<u-col v-for="item in bookshelfList" :key="item.book_id" span="4" v-show="!editFlag">
					<view @longpress.stop="longpressToEdit(access_token?item.book_shelf_id:item.book_id)">
						<shelf-card :name="item.name" :is_over="item.is_over" :percentage="item.percentage" :id="item.book_id"
						 :chapter_id="item.last_read_chapter" :image="item.image" />
					</view>
				</u-col>
				<u-col span="4" v-show="!editFlag">
					<view class="add-book" @click="handleToLibrary">
						<u-icon name="plus" size="60" color="rgb(146, 200, 255)"></u-icon>
					</view>
				</u-col>
				<u-checkbox-group @change="checkboxGroupChange" v-show="editFlag" width="33.3%" active-color="rgb(146, 200, 255)"
				 style="width:100%;align-items:flex-start;">
					<u-checkbox v-model="item.checked" v-for="(item, index) in bookshelfList" :key="index" :name="access_token?item.book_shelf_id:item.book_id"
					 shape="circle">
						<shelf-card :name="item.name" :is_over="item.is_over" :percentage="item.percentage" :id="item.id" :chapter_id="item.chapter_id"
						 :image="item.image" :opacity="editFlag?.4:1" :isClick="false" />
					</u-checkbox>
				</u-checkbox-group>
			</u-row>
			<view v-else>
				<u-empty text="您还未添加任何书籍" mode="list"></u-empty>
				<view style="font-size:28rpx;text-align:center;margin-bottom:20rpx"></view>
				<u-button :ripple="true" :custom-style="{background:'#92C8FF',color:'#ffffff'}" @click="handleToLibrary">去书城添加</u-button>
			</view>
		</view>
		<u-modal v-model="deleteShow" :content="content" show-cancel-button @confirm="handleToConfirmDelete"></u-modal>
		<u-toast ref="uToast" />
		<u-tabbar v-model="currentTabbar" :list="vuex_tabbar" v-show="!editFlag"></u-tabbar>
		<view class="detele-bottom" @click="handleToDelete" v-show="editFlag">
			删除所选({{deleteList.length}})
		</view>
	</view>
</template>

<script>
	import ShelfCard from '../../components/ShelfCard'
	import {
		getBookShelfList,
		delBookFromShelf
	} from '../../api/shelf'
	export default {
		name: 'shelf',
		data() {
			return {
				currentTabbar: 0,
				searchWrod: '',
				readTime: 0,
				editFlag: false,
				checkAllFlag: true,
				loading: false,
				bookshelfList: [],
				deleteList: [],
				deleteShow: false,
				content: ''
			}
		},
		components: {
			ShelfCard
		},
		watch: {
			bookshelfList(val) {
				if (val.length == 0) {
					this.editFlag = false;
				}
				uni.redirectTo({
					url: '/pages/shelf/shelf',
					animationType: 'none'
				})
			},
			deleteList(nVal, oVal) {
				if (nVal.length === 0) {
					this.checkAllFlag = true;
				} else {
					if (nVal.length === this.bookshelfList.length) {
						this.checkAllFlag = false;
					} else {
						this.checkAllFlag = true;
					}
				}
			},
		},
		onLoad() {
			this.loading = true;
			this.handleGetBookShelf().then(() => {
				this.getReadTime()
				this.editFlag = false;
				this.loading = false;
			})
		},
		onShow() {
			this.handleGetBookShelf().then(() => {
				this.getReadTime()
			})
		},
		onPullDownRefresh() {
			this.handleGetBookShelf().then(() => {
				this.getReadTime()
			})
			setTimeout(() => {
				this.$refs.uToast.show({
					title: '刷新成功',
					type: 'success',
					position: 'top'
				});
				uni.stopPullDownRefresh()
			}, 1000);
		},
		methods: {
			// 获取书架数据
			handleGetBookShelf() {
				return new Promise((resolve, reject) => {
					if (this.access_token) {
						let header = {
							Authorization: 'Bearer ' + this.access_token
						}
						getBookShelfList(header).then(res => {
							if (res.code == 200) {
								let _bookshelfList = []
								let _bookShelf = res.data.bookList;
								if (Object.keys(_bookShelf).length > 0) {
									for (const key in _bookShelf) {
										let percentage;
										if ((parseInt(_bookShelf[key].index)) === 0) {
											percentage = 0;
										} else if ((parseInt(_bookShelf[key].index) + 1) === parseInt(_bookShelf[key].chapter_count)) {
											percentage = 100;
										} else {
											percentage =
												((parseInt(_bookShelf[key].index) + 1) /
													parseInt(_bookShelf[key].chapter_count)) *
												100;
										}
										percentage = percentage.toFixed(1);
										_bookShelf[key].percentage = `${percentage}%`;
										_bookShelf[key].checked = false;
										_bookshelfList.push(_bookShelf[key]);
									}
								}
								this.bookshelfList = _bookshelfList;
								resolve('ok')
							} else {
								reject(res.msg)
							}
						})
					} else {
						try {
							let bookShelf = uni.getStorageSync("bookShelf");
							let _bookshelfList = [];
							if (bookShelf) {
								let _bookShelf = JSON.parse(bookShelf);
								if (Object.keys(_bookShelf).length > 0) {
									for (const key in _bookShelf) {
										let percentage =
											(parseInt(_bookShelf[key].index) /
												parseInt(_bookShelf[key].chapterCount)) *
											100;
										percentage = percentage.toFixed(1);
										_bookShelf[key].percentage = `${percentage}%`;
										_bookShelf[key].checked = false;
										_bookshelfList.push(_bookShelf[key]);
									}
								}
							}
							this.bookshelfList = _bookshelfList;
							resolve('ok')
						} catch (e) {
							reject(e)
						}
					}
				})
			},
			// 去搜索页
			handleToSearch() {
				uni.navigateTo({
					url: `/pages/search/search`
				});
			},
			// 去书城
			handleToLibrary() {
				uni.switchTab({
					url: `/pages/library/library`
				});
			},
			// 去阅读历史
			handleToHistory() {
				uni.navigateTo({
					url: `/pages/history/history`
				});
			},
			// 编辑书架
			handleToEdit() {
				if (this.bookshelfList.length === 0) {
					this.$refs.uToast.show({
						title: '书架还是空空的呢',
						type: 'warning',
						position: 'top'
					})
					return;
				}
				this.editFlag = !this.editFlag;
			},
			longpressToEdit(id) {
				uni.vibrateShort({
					success: () => {
						if (!this.editFlag) {
							if (this.access_token) {
								this.bookshelfList.forEach(item => {
									if (item.book_shelf_id == id) {
										item.checked = true;
										this.deleteList.push(item.book_shelf_id)
									}
								})
							} else {
								this.bookshelfList.forEach(item => {
									if (item.book_id == id) {
										item.checked = true;
										this.deleteList.push(item.book_id)
									}
									console.log(this.deleteList)
								})
							}
							this.editFlag = !this.editFlag;
						}
					}
				});
			},
			checkboxGroupChange(e) {
				this.deleteList = e;
			},
			handleToCheckedAll() {
				let _deleteList = [];
				this.bookshelfList.map(val => {
					val.checked = this.checkAllFlag;
				});
				if (this.checkAllFlag) {
					if (this.access_token) {
						this.bookshelfList.forEach(item => {
							_deleteList.push(item.book_shelf_id)
						});
					} else {
						this.bookshelfList.forEach(item => {
							_deleteList.push(item.book_id)
						});
					}
				}
				this.checkAllFlag = !this.checkAllFlag;
				this.deleteList = _deleteList;
			},
			handleToDelete() {
				if (this.deleteList.length === 0) {
					this.$refs.uToast.show({
						title: '您未选择任何书籍',
						type: 'warning'
					})
				} else {
					this.content = `您确定要删除这${this.deleteList.length}本书籍吗`;
					this.deleteShow = true;
				}
			},
			handleToConfirmDelete() {
				if (this.access_token) {
					let bookShelfId = this.deleteList.join(',');
					delBookFromShelf({
						Authorization: 'Bearer ' + this.access_token
					}, {
						bookShelfId
					}).then(res => {
						if (res.code == 200) {
							this.deleteList = [];
							this.handleGetBookShelf();
						}
					})
				} else {
					let bookShelf = uni.getStorageSync("bookShelf");
					if (bookShelf) {
						let _bookShelf = JSON.parse(bookShelf);
						this.deleteList.forEach(item => {
							Object.entries(_bookShelf).forEach(([key, value]) => {
								if (item == key) {
									delete _bookShelf[item]
								}
							})
						})
						uni.setStorageSync("bookShelf", JSON.stringify(_bookShelf));
						this.deleteList = [];
						this.handleGetBookShelf();
					}
				}
			},
			handleToSave() {
				if (this.editFlag) {
					this.editFlag = false;
					this.checkAllFlag = true;
					this.bookshelfList.map(val => {
						val.checked = false;
					});
					this.deleteList = [];
				}
			},
			handleToOpen() {
				const REQUESTCODE = 1;
				const main = plus.android.runtimeMainActivity();
				const Intent = plus.android.importClass('android.content.Intent');
				const intent = new Intent(Intent.ACTION_GET_CONTENT);

				intent.setType("*/*"); //设置类型，任意类型
				//intent.setType("image/*");
				//intent.setType("audio/*"); //选择音频
				//intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）

				intent.addCategory(Intent.CATEGORY_OPENABLE);
				main.startActivityForResult(intent, REQUESTCODE);
				main.onActivityResult = function(requestCode, resultCode, data) {
					if (REQUESTCODE == requestCode) {
						var context = main;
						plus.android.importClass(data);
						// 获得文件路径
						var fileData = data.getData();
						var path = plus.android.invoke(fileData, "getPath");
						console.log("path:" + path);

						// 判断文件类型
						var resolver = context.getContentResolver();
						var fileType = plus.android.invoke(resolver, "getType", fileData);
						console.log("fileType:" + fileType);
					}
				}

			},
			// 获取阅读时间
			getReadTime() {
				let read_time = uni.getStorageSync('read_time');
				if (read_time) {
					let readTime = 0;
					let readTimeList = JSON.parse(read_time);
					readTimeList.forEach(item => {
						if (item.bookId && item.readTimeEnd && item.readTimeStart) {
							readTime += this.getTime(item.readTimeStart, item.readTimeEnd)
						}
					})
					let min = Math.floor((readTime / 1000 / 60) << 0);
					this.readTime = min;
				} else {
					this.readTime = 0;
				}
			},
			getTime(start, end) {
				return new Date(end).getTime() - new Date(start).getTime()
			},
			handleToReadTime() {
				if (this.readTime != 0) {
					uni.navigateTo({
						url: '/pages/time/time'
					})
				}
			}
		}

	}
</script>

<style lang="scss" scoped>
	.shelf-box {
		background: #F5F8FC;
		min-height: 100vh;

		.status-bar {
			height: var(--status-bar-height);
			width: 100%;
			background: #F5F8FC;
		}

		.load {
			position: fixed;
			top: 0;
			left: 0;
			height: 100vh;
			width: 100vw;
			display: flex;
			align-items: center;
			justify-content: center;
			background: white;
			z-index: 100;
		}

		.read-time {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 0 20px;
			width: 60%;
			font-size: 34rpx;
		}

		.slot-wrap {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 40%;
			padding: 0 20px;
		}

		.edit-wrap {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 100%;
			padding: 0 20px;
		}

		.box-header {
			border-radius: 0 0 40rpx 40rpx;
			background: #F5F8FC;

			.box-title {
				display: flex;
				justify-content: space-between;
				padding: 32rpx 32rpx 0rpx 32rpx;
				margin-bottom: 10rpx;
				font-family: Alibaba PuHuiTi;

				text {
					font-size: 40rpx;
					font-weight: 800;
					color: rgba(6, 27, 65, 1);
					opacity: 0.75;
				}
			}

			.top-bar {
				padding: 40rpx 32rpx 20rpx 32rpx;
				background: #F5F8FC;

				.search-box {
					display: flex;
				}
			}

		}


		.bookshelf-content {
			margin: 0rpx 40rpx 0rpx 40rpx;
			padding: 36rpx 32rpx;
			background: rgba(255, 255, 255, 1);
			border-radius: 12rpx;

			.add-book {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 240rpx;
				width: 182rpx;
				background-color: #c9d6df;
				border-radius: 12rpx;
			}

			.bookshelf-timecount {
				border-bottom: 1rpx solid rgba(6, 27, 65, 0.08);
				padding-bottom: 28rpx;
				margin-bottom: 40rpx;

				.timecount-top {
					font-size: 30rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 600;
					color: rgba(6, 27, 65, 0.75);
					margin-bottom: 46rpx;
					display: flex;
					justify-content: space-between;
					align-items: flex-start;

					.top-title {}

					.edit-button {
						.delete {
							margin-right: 10rpx;
						}

						.save {}
					}
				}
			}

			.timecount-bottom {
				display: flex;
				justify-content: space-between;
				align-items: flex-end;

				div:first-child {
					font-size: 18rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: bold;
					color: rgba(6, 27, 65, 0.75);
				}

				div:last-child {
					font-family: Alibaba PuHuiTi;
					font-weight: bold;
					color: rgba(6, 27, 65, 0.75);
					display: flex;
					align-items: center;

					span:first-child {
						font-size: 36rpx;
						line-height: 36rpx;
					}

					span:last-child {
						font-size: 18rpx;
					}
				}
			}

		}

		.detele-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 90vw;
			text-align: center;
			padding: 24rpx 32rpx;
			background: white;
			border-radius: 12rpx;
			margin: 0 5vw 40rpx 5vw;
			z-index: 10;
		}

		.delete-wrap {
			position: fixed;
			top: 0;
			left: 0;
			height: 100vh;
			width: 100vw;
			background-color: white;
			opacity: .4;
			z-index: 9;
		}
	}
</style>
